<template>
  <a-modal v-model="showGoodsTags" :width="1000" class="edit-modal" :destroyOnClose="true" :centered="true">
    <a-row>
      <a-col :md="8" :xs="24" v-show="showImg">
        <div class="skc-carousel" v-if="skcList.length > 0">
          <a-carousel arrows dots-class="slick-dots slick-thumb">
            <a slot="customPaging" slot-scope="props">
              <img :src="getImgUrl(props.i)" class="dots-imgs" />
            </a>
            <div v-for="(item, index) in skcList" :key="index" class="carousel-imgs">
              <img :src="item.imgUrl" />
            </div>
          </a-carousel>
        </div>
        <div class="skc-carousel" v-else>
          <img :src="goodsInfo.imgurl ? goodsInfo.imgurl : 'https://img.bzhz.jnbygroup.com/cloth.png'" alt="" class="no-img" />
        </div>
      </a-col>
      <a-col :md="showImg ? 16 : 24" :xs="24" style="padding-top:0px;max-height: 600px;overflow-y: auto;padding-right:12px;">
        <template v-if="loading">
          <TreeModal :treeData="perTreeData" @update="update" :currentTags="currentTags" :level="0"></TreeModal>
        </template>
      </a-col>
    </a-row>
    <div slot="footer">
      <a-button type="" @click="prev" :disabled="currentIndex == 0 ? true : false" v-show="showImg">上一个</a-button>
      <a-button type="primary" @click="save">保存</a-button>
      <a-button type="" @click="next" :disabled="currentIndex == total - 1" v-show="showImg">下一个</a-button>
    </div>
  </a-modal>
</template>
<script>
import TreeModal from './TreeModal'
import { goodsDetail, markingLabel, querySysCateTree } from '@/api/goods'
import Vue from 'vue'
import { USER_INFO } from '@/store/mutation-types'
export default {
  components: {
    TreeModal
  },
  props: {
    treeData: {
      type: Array,
      default: null
    },
    currentTotal: {
      type: Number,
      default: 0,
      required: false
    },
    total: {
      type: Number,
      default: 0,
      required: false
    },
    originTreeList: {
      type: Array,
      default: null,
      required: false
    }
  },
  data() {
    return {
      showGoodsTags: false,
      skcList: [],
      zipImg: '',
      checkArray: [],
      productId: '',
      goodsInfo: {},
      currentTags: [],
      loading: false,
      currentIndex: '',
      perTreeData: [],
      showImg: true,
      currentOthersTags: [],
      userInfo: Vue.ls.get(USER_INFO),
      sysCateTree: []
    }
  },
  watch: {
    treeData(value, oldValue) {
      console.log(value, oldValue)
      this.perTreeData = JSON.parse(JSON.stringify(value))
    },
    showGoodsTags(val) {
      if (!val) {
        this.currentTags = []
        this.checkArray = []
        this.loading = false
      }
    },
    originTreeList(val) {
      // console.log('originTreeList:', val)
    }
  },
  methods: {
    add(record, index) {
      this.edit(record)
      this.currentIndex = index
      if (this.currentIndex + 1 == this.currentTotal) {
        this.$emit('loadingPage', true)
      }
    },
    async edit(record, index) {
      this.showImg = true
      this.currentIndex = index
      this.productId = record.id
      this.currentOthersTags = []
      if (this.currentIndex + 1 == this.currentTotal) {
        this.$emit('loadingPage', true)
      }
      this.perTreeData = JSON.parse(JSON.stringify(this.treeData))
      await this.getGoodInfo(this.productId)
      await this.fetchSysCateTree()
      this.getSkc(record)

      this.initialCheckArray(this.perTreeData)
      this.loading = true
      this.showGoodsTags = true
    },
    // 从goodsDetail打开
    async detailEdit(record) {
      console.log(this.treeData)
      this.perTreeData = JSON.parse(JSON.stringify(this.treeData))
      this.showImg = false
      this.currentOthersTags = []
      this.productId = record.id

      await this.getGoodInfo(this.productId)
      await this.fetchSysCateTree()
      // console.log(this.currentTags)
      // console.log(this.perTreeData)
      this.initialCheckArray(this.perTreeData)
      this.loading = true
      this.showGoodsTags = true
    },
    getGoodInfo(id) {
      let data = {
        requestData: {
          productId: id
        }
      }
      return goodsDetail(data).then(res => {
        if (res.code == 0) {
          this.goodsInfo = res.data
          if (this.goodsInfo.label_levels) {
            this.currentTags = this.goodsInfo.label_levels
          } else {
            this.currentTags = []
          }
        } else {
          this.goodsInfo = {}
          this.$message.warning(res.msg)
        }
      })
    },
    // 获取skc图片
    getSkc(data) {
      if (data.skus && data.skus.length > 0) {
        var arr = []
        var list = data.skus.map(item => {
          const color = {
            id: item.colorno,
            name: item.color_name + '(' + item.colorno + ')',
            imgUrl: item.imgurl + this.zipImg,
            previewImgUrl: item.imgurl + this.zipImg
          }
          if (item.imgurl) {
            color.imgUrl = item.imgurl + this.zipImg
            color.previewImgUrl = item.imgurl + this.zipImg
          } else {
            color.imgUrl = 'https://img.bzhz.jnbygroup.com/cloth.png'
            color.previewImgUrl = 'https://img.bzhz.jnbygroup.com/cloth.png'
          }
          return color
        })
        // console.log(list)
        var tempArr = []
        for (var i = 0; i < list.length; i++) {
          if (tempArr.indexOf(list[i].id) === -1) {
            tempArr.push(list[i].id)
            arr.push(list[i])
          }
        }
        console.log(arr)
        this.skcList = arr
      }
    },
    // 查看大图
    getImgUrl(i) {
      return this.skcList[i].imgUrl
    },
    // 初始化CheckArray
    initialCheckArray(data) {
      // 当前已勾选
      if (this.currentTags.length > 0) {
        // let allParentCode = data.map(item => item.code)
        let arr = []
        if (this.showImg) {
          this.handleInitialArray(arr, data)
        } else {
          this.handleInitialArrayFromDetail(arr, data)
        }
        let currentEditTags = []
        for (let item of arr) {
          currentEditTags = [...currentEditTags, ...item.codes]
        }
        console.log('currentEditTags', currentEditTags)
        for (let child of this.currentTags) {
          if (!currentEditTags.includes(child)) {
            this.currentOthersTags.push(child)
          }
        }
        console.log('currentOthersTags', this.currentOthersTags)

        console.log('initialCheckArray', arr)
        this.checkArray = arr
      }
    },
    // 处理初始化CheckArray
    handleInitialArray(arr, data) {
      if (data.length > 0) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].children && data[i].children.length > 0) {
            let allLeaf = data[i].children.filter(item => item.leaf)
            // console.log(allLeaf)
            if (allLeaf.length == data[i].children.length) {
              const result = this.currentTags.filter(item => {
                if (item.indexOf(data[i].code) > -1) {
                  return item
                }
              })
              // console.log(result)
              if (result.length > 0) {
                arr.push({
                  code: data[i].code,
                  codes: result
                })
              }
            } else {
              this.handleInitialArray(arr, data[i].children)
            }
          }
        }
      }
    },
    // 处理初始化CheckArray：来自商详
    handleInitialArrayFromDetail(arr, data) {
      for (let item of data) {
        if (item.children && item.children.length > 0) {
          let allLeaf = item.children.filter(e => e.leaf)
          if (allLeaf.length == item.children.length) {
            const result = this.currentTags.filter(v => v.includes(item.code))
            if (result.length > 0) {
              arr.push({
                code: item.code,
                codes: result
              })
            }
          } else {
            this.handleInitialArrayFromDetail(arr, item.children)
          }
        }
      }
    },
    // 上一个
    prev() {
      this.$emit('updateEdit', this.currentIndex - 1)
      this.currentTags = []
      this.checkArray = []
      this.loading = false
    },
    // 下一个
    next() {
      console.log(this.currentTotal)
      if (this.currentIndex + 1 == this.currentTotal) {
        console.log('翻页')
        // this.$emit('loadingPage',true)
      } else {
        this.$emit('updateEdit', this.currentIndex + 1)
        this.currentTags = []
        this.checkArray = []
        this.loading = false
      }
    },
    // 保存
    async save() {
      if (this.sysCateTree.length == 0) {
        this.$message.warning('暂无标签类目')
        return
      }
      let arr = []
      console.log(this.checkArray)
      if (this.showImg) {
        arr = this.handleArray(this.checkArray)

        /* if (arr.length == 0) {
          arr = this.currentTags
        } */
      } else {
        for (let item of this.checkArray) {
          arr = [...arr, ...item.codes]
        }
      }
      arr = [...arr, ...this.currentOthersTags]
      console.log(arr)
      /* 202201区分为spu或skc打标 *********Start***********/
      let labelList
      if (arr.length > 0) {
        labelList = await this.classifTags(arr)
      } else {
        labelList = {
          spu: [],
          skc: []
        }
      }
      /* 202201区分为spu或skc打标 *********END***********/
      let data = {
        requestData: {
          skcCode: this.productId,
          labelList: labelList.skc,
          spuLabelList: labelList.spu,
          productId: this.goodsInfo.product_id
        },
        user_id: this.userInfo.id
      }

      markingLabel(data).then(res => {
        if (res.code == 0) {
          this.$message.success('保存成功！')
          if (!this.showImg) {
            this.showGoodsTags = false
            this.$emit('updateDetail')
          }
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    // 回传打标的值
    update(value) {
      if (this.checkArray.length > 0) {
        let result = this.checkArray.filter(item => item.code == value.code)
        if (result.length > 0) {
          const index = this.checkArray.indexOf(result[0])
          this.checkArray[index] = value
        } else {
          this.checkArray.push(value)
        }
      } else {
        this.checkArray.push(value)
      }
      console.log('update', this.checkArray)
    },
    // 处理提交的数组
    handleArray(list) {
      let arr = []
      for (let item of list) {
        arr = [...arr, ...item.codes]
      }
      return arr
    },
    // 区分tags类型
    classifTags(arr) {
      let labelList = {
        spu: [],
        skc: []
      }
      let result = this.getClassifyfromTree(labelList, this.sysCateTree, arr)
      return result
    },
    getClassifyfromTree(labelList, tree, tags) {
      for (let item of tree) {
        if (!item.leaf) {
          if (item.children && item.children.length > 0) {
            let result = item.children.filter(value => value.leaf)
            if (result.length == item.children.length) {
              for (let child of item.children) {
                if (tags.indexOf(child.code) > -1) {
                  if (child.type == 1) {
                    labelList.spu.push(child.code)
                  } else {
                    labelList.skc.push(child.code)
                  }
                }
              }
            } else {
              this.getClassifyfromTree(labelList, item.children, tags)
            }
          }
        }
      }
      return labelList
    },
    fetchSysCateTree() {
      let params = {
        code: 'B05'
      }
      return querySysCateTree(params).then(res => {
        if (res.code == 0) {
          this.sysCateTree = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.skc-carousel {
  padding-bottom: 50px;
  height: 100%;
  .carousel-imgs {
    width: 100%;
    overflow: hidden;
    img {
      height: 80%;
      width: 80%;
      object-fit: scale-down;
      margin: 0 auto;
    }
  }
  .dots-imgs {
    width: 50px;
    height: 50px;
    border: 1px solid #cdcdcd;
    padding: 5px;
  }
  .slick-next::before {
    content: '';
  }
  .slick-prev::before {
    content: '';
  }
  /deep/ .slick-next,
  /deep/ .slick-prev {
    display: none;
    width: 0;
    height: 0;
  }
  .custom-slick-arrow {
    width: 25px;
    height: 25px;
    font-size: 25px;
    color: rgb(116, 116, 116);
    background-color: transparent;
    opacity: 1;
    z-index: 2;
  }
  /deep/ .slick-dots-bottom {
    bottom: -20px;
    li {
      margin: 0 5px;
    }
  }
  .no-img {
    width: 90%;
    object-fit: scale-down;
    margin: 0 auto;
  }
}
.edit-modal {
  /deep/ .ant-modal {
    padding-bottom: 0px;
  }
  /deep/ .ant-modal-body {
    min-height: 500px;
    .ant-row {
      padding-top: 24px;
      height: 100%;
    }
  }
}
</style>

